<?php
App::import('Sanitize');

class BlogsController extends AppController{
	var $name = 'Blogs';
	var $uses = array('Blog','Comment','Reply','BlogsCategory','Draft','Userinfo','Tag','Share');

	var $autoLayout = false;

	function index(){
		$this->autoLayout = true;
	}
	/**
	 * write 发表日志
	 * 日志发表成功后返回1
	 * @access public
	 * @return void
	 */
	function write(){
		if (!empty($this->data)) {
			$this->data['Blog']['title']=Sanitize::html($this->data['Blog']['title']);
			$this->data['Blog']['keywords']=Sanitize::html($this->data['Blog']['keywords']);
			$this->data['Blog']['keywords']=Sanitize::html($this->data['Blog']['keywords'],array(' '));
			$tags = preg_split("/\s+/",$this->data['Blog']['keywords']);
			// var_dump($tags);
			if(is_array($tags)){
				foreach($tags as $tag){
					if($tag === ''){
						continue;
					}
					$this->Tag->create(array(
						'Tag' => array('user_id'=>0,'tag'=>$tag)
					));
					$this->Tag->save(array(
						'Tag' => array('user_id'=>0,'tag'=>$tag)
					));
				}
			}
			$this->data['Blog']['keywords']=implode(" ",$tags);
			$this->data['Blog']['content']=preg_replace("'<\s*script[^>]*>.*<\s*/script>'",'',$this->data['Blog']['content']);
			$this->data['Blog']['uid']=$this->Session->read('User.user_id');
			if ($this->Blog->save($this->data)) {
				$this->BlogsCategory->query("UPDATE blogs_categories SET articles=articles+1 WHERE id={$this->data['Blog']['cid']} ");
			}
			echo 1;
			$this->autoRender = false;
		}else{
			$this->set('BlogsCategorys',$this->BlogsCategory->find('all',array('conditions'=>array('user_id'=>$this->Session->read('User.user_id')),'fields'=>array('id','name'))));
		}
	}
	/**
	* 删除博文
	*@param $id
	**/
	function delete(){
		$this->autoRender = false;
		if(isset($_GET['blog_id'])){
			$id = $_GET['blog_id'];
			$result = $this->Blog->query("select cid from blogs where id = $id");
			$cid = $result[0]['blogs']['cid'];
			if($this->Blog->delete($id)){
				$this->BlogsCategory->query("UPDATE blogs_categories SET articles=articles-1 WHERE id={$cid} ");
				echo 1;
			}
			else{
				echo 0;
			}
		}
		if(isset($_GET['draft_id'])){
			$id = $_GET['draft_id'];
			if($this->Draft->delete($id)){
				echo 1;
			}
			else{
				echo 0;
			}
		}
	}
	/**
	* 编辑博客
	*    用GET方法把要编辑的文章id传入,参数名为id
	*    视图请求成功返回视图,保存成功返回1,失败返回0
	*@param $id
	**/
	function edit(){
		if(isset($_GET['id'])){
			$id = $_GET['id'];
			$blog = $this->Blog->find('first',array(
				'conditions' => array('uid'=>$this->Session->read('User.user_id'),'id'=>$id)
			));
			// var_dump($blog);
			if($blog){
				$this->set('blog',$blog);
				$this->set('BlogsCategorys',$this->BlogsCategory->find('all',array('conditions'=>array('user_id'=>$this->Session->read('User.user_id')),'fields'=>array('id','name'))));
			}else{
				echo 0;
				$this->autoRender = false;
				return;
			}
		}elseif(isset($_GET['draft_id'])){
			$id = $_GET['draft_id'];
			// $blog = $this->Draft->find('first',array(
				// 'conditions' => array('uid'=>$this->Session->read('User.user_id'),'id'=>$id)
			// ));
			$blog = $this->Draft->query("SELECT * FROM drafts as Blog WHERE uid ='{$this->Session->read('User.user_id')}' AND id = '$id' limit 1");
			// var_dump($blog[0]);
			if($blog){
				$this->set('blog',$blog[0]);
				$this->set('BlogsCategorys',$this->BlogsCategory->find('all',array('conditions'=>array('user_id'=>$this->Session->read('User.user_id')),'fields'=>array('id','name'))));
			}else{
				echo 0;
				$this->autoRender = false;
				return;
			}
		}elseif(!empty($this->data)){
			$this->data['Blog']['title']=Sanitize::html($this->data['Blog']['title']);
			$this->data['Blog']['keywords']=Sanitize::html($this->data['Blog']['keywords']);
			$this->data['Blog']['keywords']=Sanitize::html($this->data['Blog']['keywords'],array(' '));
			// var_dump($tags);
			$tags = preg_split("/\s+/",$this->data['Blog']['keywords']);
			if(is_array($tags)){
				foreach($tags as $tag){
					if($tag === ''){
						continue;
					}
					$this->Tag->create(array(
						'Tag' => array('user_id'=>0,'tag'=>$tag)
					));
					$this->Tag->save(array(
						'Tag' => array('user_id'=>0,'tag'=>$tag)
					));
				}
			}
			$this->data['Blog']['keywords']=implode(" ",$tags);
			$this->data['Blog']['content']=preg_replace("'<\s*script[^>]*>.*<\s*/script>'",'',$this->data['Blog']['content']);
			$this->data['Blog']['uid']=$this->Session->read('User.user_id');
			if($this->Blog->save($this->data)) {
				echo 1;
				$this->autoRender = false;
			}
		}else{
			echo 0;
			$this->autoRender = false;
		}
	}

	function view($id){
		$this->set('blog', $this->Blog->findById($id));
		$test = $this->Blog->read('views',$id);
		$this->Blog->id = $id;
		$this->Blog->updateAll(
		array('Blog.views' =>$test['Blog']['views']+1),
		array('Blog.id ' => $id)
		);
	}
	
	/** 
		* 处理nickname
		* 
	 */
	 function handle_nickname(&$blogs){
		$n = count($blogs);
		for($i = 0;$i<$n;$i++)
		{
			$uid = $blogs[$i]['Blog']['uid'];
			$nickname = $this->User->query("select nickname from userinfos where id = $uid");
			$blogs[$i]['Blog']['nickname'] = $nickname[0]['userinfos']['nickname'];
		}
	 }
	
	/**
		* 获取用户博文
		*@param $count 返回的条数
		*@param $start 最后的Id
		*@param $end  开始的Id
	**/
	function show_user_blog(){
		$this->autoLayout = false;
		$this->autoRender = false;
		$uid=$this->Session->read('User.user_id');
		$count =Sanitize::paranoid(isset($_GET['count'])?$_GET['count']:10);
		$start =Sanitize::paranoid(isset($_GET['start'])?$_GET['start']:NULL);
		$end =Sanitize::paranoid(isset($_GET['end'])?$_GET['end']:NULL);
		if($start == null&&$end==null)
			$return = $this->Blog->query("SELECT * FROM blogs as Blog where  uid = $uid order by id desc limit $count");
		else if($start !=null&&$end == null){
			$return = $this->Blog->query("SELECT * FROM blogs as Blog where id<=$start and uid = $uid order by id desc limit $count");
		}
		else if($start == null&&$end != null){
			$return = $this->Blog->query("SELECT * FROM blogs as Blog where id>=$end and uid = $uid order by id desc limit $count");
		}
		$this->handle_nickname($return);
		echo json_encode($return);
	}
		/** 
		* show_user_blog_by_category按标签获取博文
		* 
		* @param传入参数$_GET['cid']：目录的id
		* 
		* @return 若成功则返回json 数组。否则返回0
	 */
	function show_user_blog_by_category(){
		$this->autoLayout = false;
		$this->autoRender = false;
		$cid = $_GET['cid'];
		$uid = $this->Session->read('User.user_id');
		if(isset($cid)){
		$return = $this->Blog->find('all',array('conditions'=>array('Blog.cid'=>$cid,'uid'=>$uid)));
				//$return = $this->Blog->query("SELECT * FROM blogs as Blog where cid=$cid and uid = $uid order by id desc ");
		$this->handle_nickname($return);
		echo json_encode($return);
		}
	}
		/** 
		* show_follow_blog获取关注人的博文和他分享的文章
		* 
		* 传入查看关注人的id
		* 
		* @return 若成功则返回json 数组。否则返回0
	 */
	function show_follow_blog(){
		$this->autoLayout = false;
		$this->autoRender = false;
		$uid = $this->Session->read('User.user_id');
		$follow_id = $_GET['follow_id'];
		if(isset($follow_id)){
		$return = $this->Blog->findAllByUid($follow_id);
		$return2 = $this->Share->query("SELECT * FROM blogs as Blog,shares where shares.blog_id = Blog.id and shares.user_id = $follow_id");
		// var_dump($return);
		// var_dump($return2);
		$return = array_merge($return,$return2);
		if(empty($return)){
			echo 0;
			return ;
		}
		else{
			$this->handle_nickname($return);
			echo json_encode($return);
			}
		}
	}
	/** 
		* show_by_tag获取标签的博文
		* 
		* @param传入参数：$tag = $_GET['tag'];
		* 
		* @return 若成功则返回json 数组。否则返回0
	 */
	function show_by_tag(){
		$this->autoLayout = false;
		$this->autoRender = false;
		$tag = $_GET['tag'];
		if(isset($tag )){
		$return = $this->Blog->query("SELECT * FROM blogs as Blog WHERE keywords LIKE '%".$tag."%';");
		if(empty($return)){
			echo 0;
			return ;
		}
		else{
			$this->handle_nickname($return);
			echo json_encode($return);
		}
		}
	}
	/** 
		* @brief keep_draft 保存草稿
		* 
		* @param
		* 
		* @return 当前保存的id
	 */
	function keep_draft($draft_id = null){
		$this->autoRender = false;
		// $draft_id =Sanitize::paranoid(isset($_GET['id'])?$_GET['id']:NULL);
		if (!empty($this->data)) {
			if($draft_id == null){
				$this->data['Draft']['title']=Sanitize::html($this->data['Blog']['title']);
				$this->data['Draft']['keywords']=Sanitize::html($this->data['Blog']['keywords']);
				$this->data['Draft']['keywords']=Sanitize::html($this->data['Blog']['keywords'],array(' '));
				$this->data['Draft']['keywords']=implode(" ",preg_split("/\s+/", $this->data['Blog']['keywords']));
				$this->data['Draft']['content']=preg_replace("'<\s*script[^>]*>.*<\s*/script>'",'',$this->data['Blog']['content']);
				$this->data['Draft']['uid']=$this->Session->read('User.user_id');
				$this->Draft->save($this->data);
				$return = $this->Draft->query("select @@IDENTITY");
				echo $return[0][0]['@@IDENTITY'];
			}
			else{
				$this->Draft->id = $draft_id;
				$this->data['Draft']['title']=Sanitize::html($this->data['Blog']['title']);
				$this->data['Draft']['keywords']=Sanitize::html($this->data['Blog']['keywords']);
				$this->data['Draft']['keywords']=Sanitize::html($this->data['Blog']['keywords'],array(' '));
				$this->data['Draft']['keywords']=implode(" ",preg_split("/\s+/", $this->data['Blog']['keywords']));
				$this->data['Draft']['content']=preg_replace("'<\s*script[^>]*>.*<\s*/script>'",'',$this->data['Blog']['content']);
				$this->data['Draft']['uid']=$this->Session->read('User.user_id');
				$this->Draft->save($this->data);
				echo ($draft_id);
			}
		}
	}

	/** 
		* @brief keep_draft 显示草稿
		* 
	 */
	 function show_drafts(){
		$this->autoLayout = false;
		$this->autoRender = false;
		$uid = $this->Session->read('User.user_id');
		$return = $this->Blog->query("SELECT * FROM drafts as Blog WHERE uid = $uid");
		$this->handle_nickname($return);
		echo json_encode($return);
	}

	 
	 function showall(){
	 		$this->autoLayout = false;
			$this->autoRender = false;
			//$return = $this->Blog->query("SELECT * FROM blogs where uid = 2 ");
			//$this->handle_nickname($return);
			//print_r($return);
			//$result = $this->Blog->query("select cid from blogs where id = 2");
			//echo $result[0]['blogs']['cid'];
			//$this->Blog->query("select cid from blogs where id = 2")
		}

	}
?>
